package org.itsolutions.javaBackup;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.CountDownLatch;

import org.itsolutions.javaBackup.core.CoreController;
import org.itsolutions.javaBackup.core.CoreModule;
import org.itsolutions.javaBackup.logger.ELogLevel;
import org.itsolutions.javaBackup.logger.ILogger;
import org.itsolutions.javaBackup.logger.LoggerHelper;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Stage;
import com.google.inject.grapher.GrapherModule;
import com.google.inject.grapher.InjectorGrapher;
import com.google.inject.grapher.graphviz.GraphvizModule;
import com.google.inject.grapher.graphviz.GraphvizRenderer;

/**
 * 
 * @author Tomas Fecko
 */
public final class JavaBackupMain {

	private static final ILogger 		LOGGER = LoggerHelper.getLogger(JavaBackupMain.class);
	private static final CountDownLatch	SHUTDOWN_LATCH = new CountDownLatch(1);
	
	/**
	 * 
	 */
	private JavaBackupMain() {
	}

	/**
	 * 
	 * @param pArgs arguments
	 */
	public static void main(String[] pArgs) {
		try {
			LOGGER.log(ELogLevel.INFO, "Starting JavaBackup application.");
			Injector injector;
	        if ("true".equalsIgnoreCase(System.getProperty("rttp.stage.development"))) {
	        	injector = Guice.createInjector(Stage.DEVELOPMENT, new CoreModule());
	        } else {
	        	injector = Guice.createInjector(Stage.PRODUCTION, new CoreModule());
	        }			
			CoreController coreController = injector.getInstance(CoreController.class);
			coreController.startService();
			SHUTDOWN_LATCH.await();
			graph("/tmp/javaBackup.dot", injector);
		} catch (Exception e) {
			LOGGER.log(ELogLevel.ERROR, e);
		}
	}

	/**
	 * Stops the main thread.
	 */
	public static void shutDown() {
		SHUTDOWN_LATCH.countDown();
	}
	
	/**
	 * 
	 * @param pFilename file name
	 * @param pInjector injector
	 * @throws IOException io exception
	 */
	private static void graph(String pFilename, Injector pInjector) throws IOException {
		LOGGER.log(ELogLevel.INFO, "Creating graph of application to file:", pFilename);
		PrintWriter out = new PrintWriter(new File(pFilename), "UTF-8");

		Injector injector = Guice.createInjector(new GrapherModule(), new GraphvizModule());
		GraphvizRenderer renderer = injector.getInstance(GraphvizRenderer.class);
		renderer.setOut(out).setRankdir("TB");

		injector.getInstance(InjectorGrapher.class).of(pInjector).graph();
	}
}



